package com.lzx.iteam;

import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.*;
import android.text.method.LinkMovementMethod;
import android.text.style.ImageSpan;
import android.view.*;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.lzx.iteam.adapter.DetailCommentListAdapter;
import com.lzx.iteam.adapter.EventImageAdapter;
import com.lzx.iteam.bean.TalkListData;
import com.lzx.iteam.emotion.EmotionUtil;
import com.lzx.iteam.emotion.gif.AnimatedGifDrawable;
import com.lzx.iteam.emotion.gif.AnimatedImageSpan;
import com.lzx.iteam.widget.gridimg.MyGridView;
import com.lzx.iteam.net.AddTalkCommentMsg;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.GetTalkDetailMsg;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.util.*;
import com.lzx.iteam.widget.TextViewSpan;
import io.rong.imageloader.core.ImageLoader;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 动态详情
 * Created by Megan on 15/10/12.
 */
public class ContactsTalkDetailActivity extends Activity implements View.OnClickListener, View.OnTouchListener {


    private LinearLayout mLlBack, mLlBottomLayout, mEmotionLayout, mLlEmotionDots, mPraiseLayout;
    private ListView mLvCommentList;
    private EditText mEtCommentEdit;
    private ImageView mIvEmotiom;
    private ViewPager mVpEmotion;

    private FrameLayout mFlUserImage;
    private ImageView mIvUserImage, mIvComment, mIvPraise;
    private RelativeLayout mRlRoot;
    private TextView mTvUserName, mTvContent, mTvTime, mTvAddOnePraise, mTvSend;
    private MyGridView mGvImageGrid;
    private EventImageAdapter imageAdapter;
    //    private ListView mLvPraiseName;
    private String mThumeImage;
    private String mOriImage;
    private ArrayList<String> mOriImages = new ArrayList<String>();

    private ArrayList<Map<String, String>> mPraiseList;
    private ArrayList<Map<String, String>> mCommentList;

    private Map<String, String> mReplyMap;
    private String mSendMessage;

    private String mPraise = "";
    private String mTalkId;
    //    private PraiseNameListAdapter praiseNameListAdapter;
    private DetailCommentListAdapter commentListAdapter;

    private ImageLoader mImageLoader;

    private final int ADD_COMMENT = 1000;
    private final int ADD_PRAISE = 1001;
    private final int GET_DETAIL = 1002;
    private PreferenceUtil mPreferenceUtil;
    private String myUserName;
    private String myUserId;
    private String myUserImg;

    private EmotionUtil mEmotionUtil;

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case ADD_COMMENT:
                    if (msg.arg1 == 0) {
                        String talkAboutId = (String) msg.obj;
                        mReplyMap.put(Constants.TALK_ID, mTalkId);
                        mReplyMap.put(Constants.TALK_ABOUT_ID, talkAboutId);
                        mReplyMap.put(Constants.TALK_COMMENT, mSendMessage);
                        mReplyMap.put(Constants.TALK_USER_ID, myUserId);
                        mReplyMap.put(Constants.TALK_USER_NAME, myUserName);
                        mReplyMap.put(Constants.TALK_USER_IMG, myUserImg);
                        mReplyMap.put(Constants.TALK_CREATE_TIME, System.currentTimeMillis() / 1000 + "");
                        if (mCommentList == null) {
                            ArrayList<Map<String, String>> comments = new ArrayList<Map<String, String>>();
                            comments.add(mReplyMap);
                            mCommentList = comments;
                        } else {
                            mCommentList.add(mReplyMap);
                        }
                        commentListAdapter.bindData(mCommentList);
                        mLlBottomLayout.setVisibility(View.GONE);
                        mSendMessage = "";
                        ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(ContactsTalkDetailActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                    break;
                case ADD_PRAISE:
                    if (msg.arg1 == 0) {
                        mPraise = (String) msg.obj;
                        Map<String, String> map = new HashMap<String, String>();
                        map.put(Constants.TALK_USER_ID, myUserId);
                        map.put(Constants.TALK_USER_NAME, myUserName);
                        if ("1".equals(mPraise)) {
                            mPraiseList.add(0, map);
                            Animation animation = AnimationUtils.loadAnimation(ContactsTalkDetailActivity.this, R.anim.praise_add_one_anim);
                            mIvPraise.setImageDrawable(getResources().getDrawable(R.drawable.praise_pressed));
                            mTvAddOnePraise.setVisibility(View.VISIBLE);
                            mTvAddOnePraise.startAnimation(animation);
                            new Handler().postDelayed(new Runnable() {
                                public void run() {
                                    mTvAddOnePraise.setVisibility(View.GONE);
                                }
                            }, 1000);
//                            mIvPraise.setClickable(false);
                        } else {
                            for (Map<String, String> praise : mPraiseList) {
                                if (praise.get(Constants.TALK_USER_ID).equals(myUserId)) {
                                    mPraiseList.remove(praise);
                                    break;
                                }
                            }
                            mIvPraise.setImageDrawable(getResources().getDrawable(R.drawable.praise_normal));
                        }
                        if (mPraiseList != null && mPraiseList.size() > 0) {
                          /*  if (praiseNameListAdapter == null) {
                                praiseNameListAdapter = new PraiseNameListAdapter(ContactsTalkDetailActivity.this);
                                mLvPraiseName.setAdapter(praiseNameListAdapter);
                            }
                            praiseNameListAdapter.bindData(mPraiseList);*/
                            mPraiseLayout.removeAllViews();
                            ImageView praiseIcon = new ImageView(ContactsTalkDetailActivity.this);
                            praiseIcon.setPadding(0, 0, 8, 0);
                            praiseIcon.setImageDrawable(getResources().getDrawable(R.drawable.praise));
                            mPraiseLayout.addView(praiseIcon);
                            for (int i = mPraiseList.size() - 1; i > -1; i--) {
                                final Map<String, String> praiseMap = mPraiseList.get(i);
//                    if (talkListData.praises.size() - i < 4) {
                                final TextView praise = new TextView(ContactsTalkDetailActivity.this);
                                praise.setMovementMethod(LinkMovementMethod.getInstance());
                                praise.setTextColor(getResources().getColor(
                                        R.color.talk_item_comment_name));
                                praise.setTextSize(14);
                                praise.setPadding(2, 0, 2, 0);
                                if (i == 0) {
                                    SpannableString user = new SpannableString(praiseMap.get(Constants.TALK_USER_NAME));//回复人的名字
                                    TextViewSpan clickableSpan1 = new TextViewSpan(praiseMap.get(Constants.TALK_USER_NAME), ContactsTalkDetailActivity.this, 0,0);
                                    clickableSpan1.setInfo(praiseMap);
                                    user.setSpan(clickableSpan1, 0, praiseMap.get(Constants.TALK_USER_NAME).length(),
                                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    praise.setText(user);
                                } else {
                                    SpannableString user = new SpannableString(praiseMap.get(Constants.TALK_USER_NAME) + "、");//回复人的名字
                                    TextViewSpan clickableSpan1 = new TextViewSpan(praiseMap.get(Constants.TALK_USER_NAME) + "、", ContactsTalkDetailActivity.this, 0,0);
                                    clickableSpan1.setInfo(praiseMap);
                                    user.setSpan(clickableSpan1, 0, praiseMap.get(Constants.TALK_USER_NAME).length(),
                                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    praise.setText(user);
                                }
                                mPraiseLayout.addView(praise);
                            }
//            else {
//                        break;
//                    }
                            TextView praiseCount = new TextView(ContactsTalkDetailActivity.this);
                            praiseCount.setTextColor(getResources().getColor(
                                    R.color.talk_item_comment_content));
                            praiseCount.setTextSize(14);
                            praiseCount.setPadding(2, 0, 2, 0);
                            //praiseCount.setText("等" + mPraiseList.size() + "人点赞");
                            praiseCount.setText("点赞");
                            mPraiseLayout.addView(praiseCount);
                            if (mPraiseLayout.getVisibility() == View.GONE) {
                                mPraiseLayout.setVisibility(View.VISIBLE);
                            }
                        } else {
                            mPraiseLayout.setVisibility(View.GONE);
                        }
                    }
                    break;
                case GET_DETAIL:
                    if (msg.arg1 == 0) {
                        TalkListData talkDate = (TalkListData) msg.obj;
                        setData(talkDate);
                    }
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contacts_talk_detail_layout);
        initView();
        initEmotion();
        getIntentData();
    }

    private void initView() {
        mPreferenceUtil = PreferenceUtil.getInstance(this);
        myUserId = mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "－1");
        myUserName = ((ArrayList<String>) mPreferenceUtil.getCloudContact(Constants.CONTACT_NAME_CARD)).get(0);
        myUserImg = mPreferenceUtil.getString(PreferenceUtil.NAMECARD_AVATAR, "");
        mRlRoot = (RelativeLayout) findViewById(R.id.contact_talk_detail_root_layout);
        mLlBack = (LinearLayout) findViewById(R.id.talk_detail_back);
        mLvCommentList = (ListView) findViewById(R.id.lv_talk_detail_reply);
        mLlBottomLayout = (LinearLayout) findViewById(R.id.ll_talk_detail_bottom);
        mEtCommentEdit = (EditText) findViewById(R.id.et_talk_detail_input);
        mIvEmotiom = (ImageView) findViewById(R.id.iv_talk_detail_emotion);
        mEmotionLayout = (LinearLayout) findViewById(R.id.ll_talk_detail_emotion);
        mVpEmotion = (ViewPager) findViewById(R.id.talk_detail_emotion_viewpager);
        mLlEmotionDots = (LinearLayout) findViewById(R.id.talk_detail_emotion_dots_container);
        mTvSend = (TextView) findViewById(R.id.tv_talk_detail_send);
        mRlRoot.setOnClickListener(this);
        mLvCommentList.setOnTouchListener(this);
        mTvSend.setOnClickListener(this);
        mLlBack.setOnClickListener(this);
        mIvEmotiom.setOnClickListener(this);
        mEtCommentEdit.setOnClickListener(this);
        mEtCommentEdit.requestFocus();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        mEtCommentEdit.addTextChangedListener(mTextWatcher);

/*
        mEtCommentEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEND) {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(ContactsTalkDetailActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    if (!StringUtil.isEmpty(textView.getText().toString().trim())) {
                        if (!StringUtil.isEmpty(mReplyUId)) {
                            AddReplyMsg(textView.getText().toString().trim());
                        } else {
                            AddCommentMsg(textView.getText().toString().trim());
                        }
                        mEtCommentEdit.setText("");
                        return true;
                    } else {
                        Toast.makeText(ContactsTalkDetailActivity.this, "评论内容不能为空", Toast.LENGTH_SHORT).show();
                        return false;
                    }

                } else {
                    return false;
                }

            }
        });
*/
        mImageLoader = ImageLoader.getInstance();
        mLvCommentList.addHeaderView(addHeaderView());
    }

    private void initEmotion(){
        mEmotionUtil = new EmotionUtil(this, mEtCommentEdit, mLlEmotionDots, mVpEmotion);
        mEmotionUtil.initStaticFaces();
        mEmotionUtil.initViewPager();
        mVpEmotion.setOnPageChangeListener(mEmotionUtil.new PageChange());
    }



    TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            String mSendMessage = mEtCommentEdit.getText().toString().trim();
            if (!StringUtil.isEmpty(mSendMessage)) {
                mTvSend.setVisibility(View.VISIBLE);
            } else {
                mTvSend.setVisibility(View.GONE);
            }

        }
    };


    private void getIntentData() {
        Intent intent = getIntent();
        mTalkId = intent.getStringExtra("talk_id");
        getTalkDetail();

    }

    private void setData(TalkListData talkListData) {
        mThumeImage = talkListData.thumbImage;
        mOriImage = talkListData.oriImage;
        String[] images = null;
        if (!StringUtil.isEmpty(mThumeImage)) {
            images = mThumeImage.split(",");
        }

        String[] oriImage = null;
        if (!StringUtil.isEmpty(mOriImage)) {
            oriImage = mOriImage.split(",");
            for (int i = 0; i < oriImage.length; i++) {
                mOriImages.add(oriImage[i]);
            }
        }
        mPraiseList = talkListData.praises;
        mCommentList = talkListData.comments;
        mTvUserName.setText(talkListData.uName);
        SpannableStringBuilder sb = handler(mTvContent,
                talkListData.text);
        mTvContent.setText(sb);

        mTvTime.setText(DateUtil.getChatTime(Long.parseLong(talkListData.createTime) * 1000));
        mImageLoader.displayImage(talkListData.uImage, mIvUserImage, ImageLoaderInterface.optionHeadImage);

        if (mPraiseList != null && mPraiseList.size() > 0) {
//            praiseNameListAdapter = new PraiseNameListAdapter(this);
//            praiseNameListAdapter.bindData(mPraiseList);
//            mLvPraiseName.setAdapter(praiseNameListAdapter);
            mPraiseLayout.setVisibility(View.VISIBLE);
            mPraiseLayout.removeAllViews();
            ImageView praiseIcon = new ImageView(this);
            praiseIcon.setPadding(0, 0, 8, 0);
            praiseIcon.setImageDrawable(getResources().getDrawable(R.drawable.praise));
            mPraiseLayout.addView(praiseIcon);
            for (int i = talkListData.praises.size() - 1; i > -1; i--) {
                final Map<String, String> praiseMap = talkListData.praises.get(i);
//                    if (talkListData.praises.size() - i < 4) {
                final TextView praise = new TextView(this);
                praise.setMovementMethod(LinkMovementMethod.getInstance());
                praise.setTextColor(getResources().getColor(
                        R.color.talk_item_comment_name));
                praise.setTextSize(14);
                praise.setPadding(2, 0, 2, 0);
                if (i == 0) {
                    SpannableString user = new SpannableString(praiseMap.get(Constants.TALK_USER_NAME));//回复人的名字
                    TextViewSpan clickableSpan1 = new TextViewSpan(praiseMap.get(Constants.TALK_USER_NAME), this, 0,0);
                    clickableSpan1.setInfo(praiseMap);
                    user.setSpan(clickableSpan1, 0, praiseMap.get(Constants.TALK_USER_NAME).length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    praise.setText(user);
                } else {
                    SpannableString user = new SpannableString(praiseMap.get(Constants.TALK_USER_NAME) + "、");//回复人的名字
                    TextViewSpan clickableSpan1 = new TextViewSpan(praiseMap.get(Constants.TALK_USER_NAME) + "、", this, 0,0);
                    clickableSpan1.setInfo(praiseMap);
                    user.setSpan(clickableSpan1, 0, praiseMap.get(Constants.TALK_USER_NAME).length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    praise.setText(user);
                }
                mPraiseLayout.addView(praise);
            }
//            else {
//                        break;
//                    }
            TextView praiseCount = new TextView(this);
            praiseCount.setTextColor(getResources().getColor(
                    R.color.talk_item_comment_content));
            praiseCount.setTextSize(14);
            praiseCount.setPadding(2, 0, 2, 0);
            //praiseCount.setText("等" + talkListData.praises.size() + "人点赞");
            praiseCount.setText("点赞");
            mPraiseLayout.addView(praiseCount);
        } else {
            mPraiseLayout.setVisibility(View.GONE);
        }

        commentListAdapter = new DetailCommentListAdapter(this);
        commentListAdapter.bindData(mCommentList);
        mLvCommentList.setAdapter(commentListAdapter);
        if (images != null && images.length > 0) {
            mGvImageGrid.setVisibility(View.VISIBLE);
            imageAdapter = new EventImageAdapter(this, images,"");
            mGvImageGrid.setAdapter(imageAdapter);
        } else {
            mGvImageGrid.setVisibility(View.GONE);
        }

        if ("1".equals(talkListData.isPraise)) {
            mIvPraise.setImageDrawable(getResources().getDrawable(R.drawable.praise_pressed));
        } else {
            mIvPraise.setImageDrawable(getResources().getDrawable(R.drawable.praise_normal));
        }
    }


    private View addHeaderView() {
        View view = LayoutInflater.from(this).inflate(R.layout.talk_detail_header, null);
        mIvUserImage = (ImageView) view.findViewById(R.id.talk_detail_user_img);
        mFlUserImage = (FrameLayout) view.findViewById(R.id.talk_detail_user_img_fl);
        mIvComment = (ImageView) view.findViewById(R.id.iv_talk_detail_comment);
        mIvPraise = (ImageView) view.findViewById(R.id.iv_talk_detail_praise);
        mTvUserName = (TextView) view.findViewById(R.id.talk_detail_user_name);
        mTvContent = (TextView) view.findViewById(R.id.talk_detail_content);
        mTvTime = (TextView) view.findViewById(R.id.talk_detail_user_time);
        mTvAddOnePraise = (TextView) view.findViewById(R.id.tv_talk_detail_praise_add_one);
        mGvImageGrid = (MyGridView) view.findViewById(R.id.talk_detail_gv_image);
//        mLvPraiseName = (ListView) view.findViewById(R.id.lv_talk_detail_praise_list);
        mPraiseLayout = (LinearLayout) view.findViewById(R.id.lv_talk_detail_praise_layout);
        mIvComment.setOnClickListener(this);
        mFlUserImage.setOnClickListener(this);
        mIvPraise.setOnClickListener(this);
        mGvImageGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(ContactsTalkDetailActivity.this, ImagePagerActivity.class);
                intent.putExtra(Constants.IMAGE_ORIGIN, Constants.IMAGE_ORIGIN_URL_ARRAY);
                intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, mOriImages);
                intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, i);
                startActivity(intent);

            }
        });
        return view;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.talk_detail_back:
                finish();
                break;
            case R.id.iv_talk_detail_emotion:
                try {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(ContactsTalkDetailActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                boolean visible = mEmotionLayout.getVisibility() == View.VISIBLE;
                mEmotionLayout.setVisibility(visible ? View.GONE : View.VISIBLE);
                break;
            case R.id.iv_talk_detail_praise:
                AddPraiseMsg();
                break;
            case R.id.iv_talk_detail_comment:
                if (mLlBottomLayout.getVisibility() == View.VISIBLE) {
                    mLlBottomLayout.setVisibility(View.GONE);
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(ContactsTalkDetailActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } else {
                    mEtCommentEdit.setHint("说点什么吧");
                    mReplyMap = new HashMap<String, String>();
                    mReplyMap.put(Constants.TALK_TYPE, "2");
                    mLlBottomLayout.setVisibility(View.VISIBLE);
                    mEtCommentEdit.requestFocus();
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                }

                break;
            case R.id.et_talk_detail_input:
                visible = (mEmotionLayout.getVisibility() == View.VISIBLE);
                if (visible) {
                    mEmotionLayout.setVisibility(View.GONE);
                }
                break;
            case R.id.talk_detail_user_img_fl:

                break;

            case R.id.tv_talk_detail_send:
                ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(ContactsTalkDetailActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                if (!StringUtil.isEmpty(mEtCommentEdit.getText().toString().trim())) {
                    mSendMessage = mEtCommentEdit.getText().toString().trim();
                    if ("2".equals(mReplyMap.get(Constants.TALK_TYPE))) {
                        AddCommentMsg(mSendMessage, 2);
                    } else {
                        AddCommentMsg(mSendMessage, 3);
                    }
                    mEtCommentEdit.setText("");
                } else {
                    Toast.makeText(ContactsTalkDetailActivity.this, "评论内容不能为空", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.contact_talk_detail_root_layout:
                visible = (mLlBottomLayout.getVisibility() == View.VISIBLE);
                if (visible) {
                    mLlBottomLayout.setVisibility(View.GONE);
                }
                break;
        }
    }


    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (view.getId()) {
            case R.id.lv_talk_detail_reply:
                try {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(ContactsTalkDetailActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mLlBottomLayout.setVisibility(View.GONE);
                break;
        }
        return false;
    }


    /**
     * 表情页改变时，dots效果也要跟着改变
     */
    class PageChange implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int arg0) {
            for (int i = 0; i < mLlEmotionDots.getChildCount(); i++) {
                mLlEmotionDots.getChildAt(i).setSelected(false);
            }
            mLlEmotionDots.getChildAt(arg0).setSelected(true);
        }

    }

    private SpannableStringBuilder handler(final TextView gifTextView, String content) {
        SpannableStringBuilder sb = new SpannableStringBuilder(content);
        String regex = "(\\#\\[face/png/f_static_)\\d{3}(.png\\]\\#)";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(content);
        while (m.find()) {
            String tempText = m.group();
            try {
                String num = tempText.substring("#[face/png/f_static_".length(), tempText.length() - ".png]#".length());
                String gif = "face/gif/f" + num + ".gif";
                /**
                 * 如果open这里不抛异常说明存在gif，则显示对应的gif
                 * 否则说明gif找不到，则显示png
                 * */
                InputStream is = getAssets().open(gif);
                sb.setSpan(new AnimatedImageSpan(new AnimatedGifDrawable(is, new AnimatedGifDrawable.UpdateListener() {
                            @Override
                            public void update() {
                                gifTextView.postInvalidate();
                            }
                        })), m.start(), m.end(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                is.close();
            } catch (Exception e) {
                String png = tempText.substring("#[".length(), tempText.length() - "]#".length());
                try {
                    int resID = getResources().getIdentifier(png.split("/")[2].substring(0, png.split("/")[2].indexOf(".")), "drawable", getApplicationInfo().packageName);
                    sb.setSpan(new ImageSpan(ContactsTalkDetailActivity.this, BitmapFactory.decodeResource(getResources(), resID)), m.start(), m.end(),
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

//                    sb.setSpan(new ImageSpan(ContactsTalkDetailActivity.this, BitmapFactory.decodeStream(getAssets().open(png))), m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
//                e.printStackTrace();
            }
        }
        return sb;
    }


    private void AddCommentMsg(String content, int type) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TALK_ID, mTalkId));
        AddTalkCommentMsg message = new AddTalkCommentMsg(mHandler.obtainMessage(ADD_COMMENT), this);
        if (type == 2) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CONTENT, content));
            message.mApi = AsynHttpClient.API_TALK_ADD_COMMENT;
        } else {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_REPLY_UID, mReplyMap.get(Constants.TALK_REPLY_ID)));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_REPLY_TXT, content));
            message.mApi = AsynHttpClient.API_TALK_REPLY;
        }
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execTalkHttp(message);
    }


    private void AddPraiseMsg() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TALK_ID, mTalkId));
        AddTalkCommentMsg message = new AddTalkCommentMsg(mHandler.obtainMessage(ADD_PRAISE), ContactsTalkDetailActivity.this);
        message.mApi = AsynHttpClient.API_TALK_LIKE;
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execTalkHttp(message);
    }


    private void getTalkDetail() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TALK_ID, mTalkId));
        GetTalkDetailMsg message = new GetTalkDetailMsg(mHandler.obtainMessage(GET_DETAIL), ContactsTalkDetailActivity.this);
        message.mApi = AsynHttpClient.API_TALK_DETAIL;
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execTalkHttp(message);
    }


    public void showBottomLayout(Map<String, String> replyMap) {
        mLlBottomLayout.setVisibility(View.VISIBLE);
        ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
//        mReplyMap.clear();
        mReplyMap = new HashMap<String, String>();
        mReplyMap = replyMap;
        mEtCommentEdit.setText("");
        mEtCommentEdit.requestFocus();
        if ("2".equals(replyMap.get(Constants.TALK_TYPE))) {
            mEtCommentEdit.setHint("说点什么吧");
        } else {
            mEtCommentEdit.setHint("回复" + replyMap.get(Constants.TALK_REPLY_NAME));
        }
    }


}
